package com.zkdcloud.controller.mobile;

import com.alibaba.fastjson.JSONObject;
import com.xdja.interceptor.annotation.BeforeProcess;
import com.zkdcloud.aspectInterceptor.advice.MobileTokenAdvice;
import com.zkdcloud.domain.*;
import com.zkdcloud.dto.*;
import com.zkdcloud.service.*;
import com.zkdcloud.util.DateUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

import static com.zkdcloud.constant.Constants.HTTP_CONSTANTS.REQUEST_USER;
import static com.zkdcloud.dto.OrderStatus.STATUS_WAIT_ACCEPT;
import static com.zkdcloud.dto.OrderStatus.STATUS_WAIT_PAYMENT;
import static com.zkdcloud.dto.OrderStatus.STATUS_WAIT_SUBMIT;

/**
 * @author zk123
 * @version 2018/5/16
 */
@RestController
@RequestMapping(value = "/api")
@BeforeProcess(advice = MobileTokenAdvice.class)
public class MobileOrderController {
    /**
     * cartService
     */
    @Autowired
    private CartService cartService;
    /**
     * 地址service
     */
    @Autowired
    private AddressService addressService;
    /**
     * user Service
     */
    @Autowired
    private UserService userService;
    /**
     * orderService
     */
    @Autowired
    private OrderService orderService;
    /**
     * businessService
     */
    @Autowired
    private BusinessService businessService;

    @RequestMapping(value = "/orders/all", method = RequestMethod.GET)
    public Object getOrders(String page, String size, Map<String,Object> map) {
        //?expand=business_info,cart_info
        User user = (User) map.get(REQUEST_USER);
        List<TerminalOrder> terminalOrderList = orderService.getTerminalOrderListByUid(user.getId());
        TerminalResultsPage<TerminalOrder> result = new TerminalResultsPage<>(9, 8, 1, 10);
        result.setItems(terminalOrderList);
        return result;
    }

    /**
     * 获取订单详情
     *
     * @param id id
     * @return cartInfo
     */
    @RequestMapping(value = "/orders/cartInfo/{id}")
    public Object getCarInfo(@PathVariable String id,Map<String,Object> map) {
        TerminalOrder result = orderService.getTerminalOrder(id);
        return result;
    }

    @BeforeProcess(advice = MobileTokenAdvice.class)
    @RequestMapping(value = "/orders/check",method = RequestMethod.POST)
    public Object checkOrder(String businessId, String payMethod, String productList, Map<String,Object> map){
        SettleResult settleResult = new SettleResult();
        User user = userService.getById(((User) map.get(REQUEST_USER)).getId());
        List<QueryCartCheck> queryCartChecks = JSONObject.parseArray(productList,QueryCartCheck.class);

        //保存购物车
        Map<String,String> cartParameMap = new HashMap<>();
        cartParameMap.put("businessId",businessId);
        cartParameMap.put("payMethod",payMethod);
        cartParameMap.put("lastAddressId",user.getLastAddressId());
        String cartId = null;
        try {
            cartId = cartService.saveCart(queryCartChecks,cartParameMap);
            //保存产品
            cartService.saveCartProduct(queryCartChecks,cartId);
            settleResult.setCanSubmit(true);
        } catch (Exception e) {
            settleResult.setCanSubmit(false);
            settleResult.setErrorTip(e.getMessage());
        }


        //组装返回的结果
        settleResult.setCartInfo(cartService.getBaseCartInfo(cartId));
        settleResult.setLastAddress(addressService.getById(user.getLastAddressId()));
        settleResult.setOnlinePayment(true);
        settleResult.setBookingTimeList(Arrays.asList(
                new BookingTime((System.currentTimeMillis() + 1000*60*15 )/1000, DateUtil.getHourLevelFormat(System.currentTimeMillis() + 1000*60*15),"15分钟内"),
                new BookingTime((System.currentTimeMillis() + 1000*60*30 )/1000, DateUtil.getHourLevelFormat(System.currentTimeMillis() + 1000*60*30),"30分钟内")
        ));
        return settleResult;
    }

    /**
     * 提交订单
     *
     * @param cartId cartId
     * @param bookTime bookTime
     * @param remark remark
     * @return order
     */
    @BeforeProcess(advice = MobileTokenAdvice.class)
    @RequestMapping(value = "/orders/submit",method = RequestMethod.POST)
    public Object orderSubmit(String cartId,Long bookTime,String remark,HttpServletRequest request){
        User user = userService.getById(((User) request.getAttribute(REQUEST_USER)).getId());
        TerminalCartInfo terminalCartInfo = cartService.getBaseCartInfo(cartId);

        //提交订单
        Order order = new Order();
        order.setBusinessId(terminalCartInfo.getBusinessInfo().getId());
        order.setUserId(user.getId());

        Address address = addressService.getById(user.getLastAddressId());
        order.setAddress(address.getName() + "," + address.getSummary() + "," + address.getDetail() + "," + address.getPhone());
        order.setBookTime(bookTime);
        order.setCartId(cartId);
        order.setConsignee(user.getNickname());
        order.setDiscountPrice(terminalCartInfo.getDiscountPrice());
        order.setOriginPrice(terminalCartInfo.getOriginPrice());
        order.setTotalPrice(terminalCartInfo.getTotalPrice());
        order.setPayMethod("1");
        order.setPhone(user.getMobile());
        order.setRemark(remark);
        order.setStatus(STATUS_WAIT_PAYMENT.getValue());
        orderService.add(order);

        //封装结果
        TerminalOrder terminalOrder = new TerminalOrder();
        BeanUtils.copyProperties(order,terminalOrder);
        terminalOrder.setBusinessInfo(businessService.get(order.getBusinessId()));
        terminalOrder.setCartInfo(terminalCartInfo);
        return terminalOrder;
    }

    @RequestMapping(value ="/orders/payments",method = RequestMethod.POST)
    public Object pay(String orderId,String platformId,String amount){
        orderService.changeStatus(orderId, String.valueOf(STATUS_WAIT_ACCEPT.getValue()));
        return new Object();
    }
}
